<template>
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="任务单号">
          <el-input v-model="searchParam.code" placeholder="请输入任务单号" clearable style="width: 220px"/>
        </el-form-item>
        <el-form-item label="入库仓库">
          <el-tree-select v-model="searchParam.wareId" :data="wareList" check-strictly filterable
                          :render-after-expand="false" :props="{
							children: 'sonList',
							label: 'warehouseName',
							value: 'id',
						}" style="width: 201px" @change="wareSearchChange"/>
        </el-form-item>
        <el-form-item label="入库库位">
          <el-select v-model="searchParam.targetStorageId" filterable multiple clearable collapse-tags collapse-tags-tooltip
                     max-collapse-tags="2" placeholder="请选择入库库位" style="width: 310px">
            <el-option v-for="item in searchStorageList" :key="item.id" :label="item.storageName"
                       :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-select v-model="searchParam.businessType" filterable placeholder="请选择业务类型" style="width: 201px">
            <el-option v-for="item in businessTypeList" :key="item.id" :label="item.name"
                       :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="委外单号">
          <el-input v-model="searchParam.outsourcingNo" placeholder="请输入委外单号" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="单据状态" prop="businessType">
          <el-select v-model="searchParam.statusCodes" multiple filterable placeholder="请选择单据状态" style="width: 220px">
            <el-option :key="1" label="待处理"
                       :value="1"/>
            <el-option :key="2" label="进行中"
                       :value="2"/>
            <el-option :key="3" label="完结"
                       :value="3"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          <div>列表信息</div>
        </div>
        <div class="pageTableButView">
          <el-button @click="handleAdd" :icon="Plus">新建</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="paginatedData" height="calc(100vh - 370px)" row-key="id" :stripe="false"
                @expand-change="handleExpandChange" header-cell-class-name="witheTableHeader">
        <el-table-column type="expand">
          <template #default="scope">
            <!--            子级列表-->
            <div m="4">
              <el-table ref="tableCil" :stripe="false" border size="small" :data="scope.row.children"
                        style="width: 95%;margin-left: 20px" header-cell-class-name="blueTableHeader">
                <!-- <el-table-column width="45" align="center">
                  <template #default="scopes">
                    <el-checkbox @change="handleSelectionChange(scopes.row)" />
                  </template>
</el-table-column> -->
                <el-table-column type="index" width="80" align="center" label=""/>
                <el-table-column label="物料名称" prop="materialName" min-width="150" align="center"
                                 show-overflow-tooltip/>
                <el-table-column type label="需求数量" prop="materialCount" min-width="100" align="center"
                                 show-overflow-tooltip/>
                <el-table-column label="实际入库数量" prop="actualOutCount" min-width="150" align="center"
                                 show-overflow-tooltip/>
                <el-table-column label="批次号" prop="batchNo" min-width="180" align="center"
                                 show-overflow-tooltip/>
                <el-table-column label="质检状态" prop="qualityStatus" min-width="180" align="center"
                                 show-overflow-tooltip/>
                <el-table-column label="" min-width="120" align="center"
                                 v-if="scope.row.allotStatus != 3">
                  <template #default="scopes">
                    <el-button type="text" size="small" :icon="DocumentCopy
											" @click="doQuality(scopes.row, scope.row)">质检
                    </el-button>
                    <el-button type="text" size="small" :icon="Files"
                               :disabled="scopes.row.activate" @click="doOutIn(scopes.row)">入库
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope"> {{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="任务单号" prop="code" min-width="150" show-overflow-tooltip align="center"/>
        <el-table-column label="业务类型" prop="businessOutType" :formatter="transferTypeFormatter" min-width="100"
                         show-overflow-tooltip align="center"/>
        <el-table-column label="委外单号" prop="outsourcingNo" min-width="150" show-overflow-tooltip
                         align="center"/>
        <!--            <el-table-column label="出库库位" prop="sourceStorageName" min-width="150" show-overflow-tooltip-->
        <!--                             align="center"/>-->
        <el-table-column label="入库库位" prop="targetStorageName" min-width="150" show-overflow-tooltip
                         align="center"/>
        <el-table-column label="数量" prop="materialCount" min-width="150" show-overflow-tooltip
                         align="center"/>
        <!--				<el-table-column label="创建人" prop="createUser" min-width="150" show-overflow-tooltip align="center" />-->
        <el-table-column label="创建时间" prop="createTime" min-width="150" show-overflow-tooltip align="center"/>
        <!--        <el-table-column prop="status" label="状态" width="100">-->
        <!--          <template #default="scope">-->
        <!--            {{ scope.row.status === 0 ? '未完成' : '已完成' }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="allotStatus" align="center" min-width="80" label="单据状态"
                         :formatter="formatStatus"/>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" :icon="Tickets" @click="handleEdit(scope.row, 1)">详情
            </el-button>
            <el-button type="text" size="small" :icon="DocumentChecked
							" @click="doFinish(scope.row)" v-if="scope.row.allotStatus != 3">完结
            </el-button>
            <!--            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>-->
            <!--            <el-button type="text" size="small" @click="handleDel(scope.row)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background layout="sizes, prev,pager, next,total" :total="pageTotal" :page-size="pageSize"
                       :current-page="currentPage" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 编辑/新建弹框 -->
    <el-dialog v-model="showCrud" :title="crudTitle + '入库单'" width="80%">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-row :gutter="10">
          <!-- <el-col :span="8">
            <el-form-item label="工序订单" prop="procedureOrderId">
              <el-select v-model="formData.procedureOrderId" placeholder="请选择工序订单" clearable filterable
                style="width: 201px" :disabled="popType == 1">
                <el-option v-for="item in procedureOrderList" :key="item.id" :label="item.no"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="入库仓库">
              <el-tree-select v-model="formData.wareId" :data="wareList" :disabled="popType == 1" filterable
                              placeholder="请选择入库仓库" check-strictly :render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" style="width: 201px" @change="wareChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库库位" prop="targetStorageId" required>
              <el-select v-model="formData.targetStorageId" :disabled="popType == 1" placeholder="请选择入库库位" filterable
                         style="width: 201px">
                <el-option v-for="item in storageList" :key="item.id" :label="item.storageName"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务类型" prop="businessType" required>
              <el-select v-model="formData.businessType" filterable placeholder="请选择业务类型"
                         style="width: 201px">
                <el-option v-for="item in businessTypeList" :key="item.id" :label="item.name"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="formData.businessType == 6">
            <el-form-item label="委外单号" required prop="outsourcingId">
              <el-select v-model="formData.outsourcingId" filterable placeholder="请选择委外单号"
                         style="width: 201px">
                <el-option v-for="item in outsourcingList" :key="item.id" :label="item.outsourcingNo"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="formData.businessType == 6 || formData.businessType == 1">
            <el-form-item label="供应商" required prop="supplierId">
              <el-select v-model="formData.supplierId" filterable placeholder="请选择供应商"
                         style="width: 201px">
                <el-option v-for="item in supplierList" :key="item.id" :label="item.name"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <div class="pageTableTitle">物料列表</div>
        </el-row>
        <el-row :gutter="10" style="padding: 10px">
          <el-table :data="formData.details" style="width:100% " height="300px">
            <el-table-column label="序号" type="index" align="center" width="80"/>
            <el-table-column prop="materialId" label="物料编码" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.materialId" :disabled="popType == 1" placeholder="请选择物料" remote
                           :remote-method="(query) => remoteMateriaList(scope.$index, query)"
                           clearable filterable @change="getMaterialInfo(scope.$index)">
                  <el-option v-for="item in scope.row.materiaList" :key="item.id" :label="item.materialName"
                             :value="item.id"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="basicUnit" label="单位" align="center"/>
            <el-table-column prop="materialCount" label="数量" align="center" width="200">
              <template #default="scope">
                <el-input-number :min="0" v-model="scope.row.materialCount" :disabled="popType == 1"
                                 style="width: 100%;" placeholder=""/>
              </template>
            </el-table-column>
            <el-table-column prop="batch" label="GRN编号" align="center">
              <template #default="scope">
                <el-input class="center-input" v-model="scope.row.batch" placeholder=""
                          :disabled="popType == 1" style="width: 100%"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="heatNumber" label="炉号" align="center">
              <template #default="scope">
                <el-input class="center-input" v-model="scope.row.heatNumber" placeholder=""
                          :disabled="popType == 1" style="width: 100%"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
              <template #header>
                <el-button :icon="Plus" text @click="handleAddConfigLine">新建</el-button>
              </template>
              <template #default="scope">
                <!--                <el-button @click="handleEditConfigLine(scope.row,scope.$index)"-->
                <!--                           plain :icon="Edit">-->
                <!--                  编辑-->
                <!--                </el-button>-->
                <el-button type="danger" plain text :icon="Delete"
                           @click="handleConfigDelete(scope.$index)"> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave(formRef)">保存</el-button>
				</span>
      </template>
    </el-dialog>
    <!-- 查看详情弹框 -->
    <el-dialog v-model="showDetail" :title="crudTitle + '入库单'" width="85%" top="3vh">
      <el-form :model="formData" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="工序订单："> {{ formData.procedureOrderNo || '--' }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库仓库："> {{ formData.targetWarehouseName || '--' }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库库位："> {{ formData.targetStorageName || '--' }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务类型："> {{ transferTypeFormatter(formData) || '--' }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委外单号："> {{ formData.outsourcingNo || '--' }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商："> {{ formData.supplierName || '--' }}</el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="10">
          <div class="pageTableTitle">物料列表</div>
        </el-row> -->
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="入库订单明细" name="detail">
            <div style="display: flex;align-items: center;padding-bottom: 10px;">
              <el-button type="primary" @click="doPrintShow" :disabled="multipleSelection.length == 0"
                         style="margin-left: auto;">打印
              </el-button>
            </div>
            <el-table :data="formData.details" @selection-change="handleSelectionChange" style="width:100% "
                      height="400px">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="序号" type="index" align="center" width="80"/>
              <el-table-column prop="materialName" label="物料名称" align="center"/>
              <el-table-column prop="materialCount" label="数量" align="center" width="150"/>
              <el-table-column prop="basicUnit" label="单位" align="center"/>
              <el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
                <template #header>
                  <el-button :icon="Plus" @click="handleAddConfigLine">新建</el-button>
                </template>
                <template #default="scope">
                  <el-button type="danger" plain :icon="Delete"
                             @click="handleConfigDelete(scope.$index)"> 删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="二维码补打" name="qrCode">
            <div style="display: flex;align-items: center;padding-bottom: 10px;justify-content: flex-end">
              <el-button type="danger" @click="printDelete(multipleCodeSelection)"
                         :disabled="multipleCodeSelection.length == 0"
              >二维码删除
              </el-button>
              <el-button type="primary" @click="printClick(multipleCodeSelection)"
                         :disabled="multipleCodeSelection.length == 0"
              >二维码补打
              </el-button>
            </div>
            <el-table :data="formData.warehouseMaterialTransferOrderDetailBatchList"
                      @selection-change="handleSelectionCodeChange" style="width:100% " height="400px">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="序号" type="index" align="center" width="80"/>
              <el-table-column prop="materialName" label="物料名称" align="center"/>
              <el-table-column prop="materialCount" label="数量" align="center" width="150"/>
              <el-table-column prop="batchNo" label="批次号" align="center"/>
              <el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
                <template #header>
                  <el-button :icon="Plus" @click="handleAddConfigLine">新建</el-button>
                </template>
                <template #default="scope">
                  <el-button type="danger" plain :icon="Delete"
                             @click="handleConfigDelete(scope.$index)"> 删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="showDetail = false">关闭</el-button>
				</span>
      </template>
      <el-dialog title="打印" width="800px" v-model="showPrint" append-to-body>
        <el-form ref="printForms" :model="printForm" label-width="auto">
          <el-row :gutter="0">
            <el-col :span="12">
              <el-form-item label="SNP" prop="SNP">
                <el-input placeholder="请填写SNP" v-model="printForm.materialCount"
                          style="width: 250px;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="打印条码数" prop="SNP">
                <el-input placeholder="请填写打印条码数" v-model="printForm.batchNumber"
                          style="width: 250px;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="small" @click="showPrint = false">取 消</el-button>
            <el-button size="small" type="primary" @click="handPrint">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>
    <!-- 点击入库弹窗 -->
    <el-dialog v-model="showOutIn" title="入库" width="1000px">
      <el-form :model="outInForm" :rules="outInRules" ref="outInFormRef" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="物料名称"> {{ outInForm.materialName || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数量" prop="materialCount" required>
              <el-input v-model="outInForm.materialCount" type="number" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库仓库">
              <el-tree-select v-model="outInForm.targetWarehouseId" :data="wareList" check-strictly
                              :render-after-expand="false" :props="{
									children: 'sonList',
									label: 'warehouseName',
									value: 'id',
								}" @change="wareChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库库位" prop="targetStorageId" required>
              <el-select v-model="outInForm.targetStorageId" placeholder="请选择"
                         @change="getWorkNO(outInForm.materialId, outInForm.targetStorageId)">
                <!--                sourceStorageId-->
                <el-option v-for="item in storageList" :key="item.id" :label="item.storageName"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号"> {{ outInForm.batchNo }}</el-form-item>
          </el-col>
          <el-col :span="8" v-if="outFatherInfo.businessType == 6">
            <el-form-item label="追溯码" required>
              <el-input v-model="outInForm.traceabilityBarcode" placeholder=""></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="showOutIn = false">取消</el-button>
					<el-button type="primary" @click="outInSum(outInFormRef)">保存</el-button>
				</span>
      </template>
    </el-dialog>
    <el-dialog v-model="showQuality" title="质检" width="800px">
      <el-form :model="formQuality" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="质检类型" prop="procedureOrderId">
              <el-select v-model="formQuality.qualityType" placeholder="请选择质检类型" clearable filterable
                         style="width: 300px" @change="qualityTypeChange">
                <el-option key="5" label="入库检" value="5"/>
                <el-option key="7" label="来料检" value="7"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检方案" prop="procedureOrderId">
              <el-select v-model="formQuality.qualityPlan" placeholder="请选择质检方案" clearable filterable
                         style="width: 300px" @change="qualityPlanChange">
                <el-option v-for="item in schemeTaskList" :key="item.id" :label="item.name"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检方式" prop="qualityWay">
              <el-select v-model="formQuality.qualityWay" placeholder="请选择质检方式" clearable
                         style="width: 300px" disabled>
                <el-option v-for="(item, index) of qualityWayList" :key="index" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formQuality.qualityWay == 2">
            <el-form-item label="比例抽检">
              <el-input-number v-model="formQuality.proportionNumber" disabled :min="0"/>
              （%）
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formQuality.qualityWay == 3">
            <el-form-item label="固定抽检">
              <el-input-number v-model="formQuality.qualityNumber" :step="1" step-strictly :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="方案说明" prop="qualityRemark" disabled>
              <el-input v-model="formQuality.qualityRemark" style="width: 718px" :rows="4" type="textarea"
                        disabled placeholder="请输入方案说明"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="showQuality = false">取消</el-button>
					<el-button type="primary" @click="handleQualitySave">保存</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {computed, onMounted, ref} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, DocumentChecked, Files, Plus, Refresh, Search, Tickets, DocumentCopy} from '@element-plus/icons-vue';
import moment from 'moment';

const paginatedData = ref([]);
const pageSize = ref(10);
const currentPage = ref(1);
const searchParam = ref({});
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};


const formData = ref({
  planNo: '',
  name: '',
  planBeginTime: null,
  planEndTime: null,
  actualBeginTime: null,
  actualEndTime: null,
  organizationId: '',
  status: '0',
  type: '0'
});

const crudTitle = computed(() => {
  if (popType.value === 1) {
    return '查看';
  } else {
    return isEdit.value ? '编辑' : '新建';
  }
});

const showDetail = ref(false);

const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  // if (multipleSelection.value.includes(val)) {
  // 	// 如果 multipleSelection 已经包含 val，则删除它
  // 	multipleSelection.value = multipleSelection.value.filter(item => item !== val);
  // } else {
  // 	// 如果 multipleSelection 不包含 val，则添加它
  // 	multipleSelection.value.push(val);
  // }
};

const multipleCodeSelection = ref([]);

const handleSelectionCodeChange = (val) => {
  multipleCodeSelection.value = val;
};


import {getCurrentInstance} from 'vue';

const {proxy}: any = getCurrentInstance();
// 打印 Rdelete
const printClick = (val) => {
  const templateName = 'test_print1/warehouseReceipt.cpt';
  proxy.$printClick(templateName, val);
};

const printDelete = (val) => {
  ElMessageBox.confirm('是否删除所选二维码', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        axiosInstance.delete('/api/warehouseMaterialTransferOrderDetailBatch/delete', {
          data: {
            ids: val.map(item => item.id)
          }
        }).then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功');
            val.forEach(item => {
              const index = formData.value.warehouseMaterialTransferOrderDetailBatchList.findIndex(batchItem => batchItem.id === item.id);
              if (index !== -1) {
                formData.value.warehouseMaterialTransferOrderDetailBatchList.splice(index, 1);
              }
            });
          }
        });
      });

};


const handPrint = () => {
  if (!printForm.value.materialCount) {
    ElMessage.error('请填写SNP');
    return false;
  }

  if (!printForm.value.batchNumber) {
    ElMessage.error('请填写打印条码数');
    return false;
  }
  // 生成批次号
  const param = multipleSelection.value.map(item => {
    return {
      materialTransferOrderDetailId: item.id,
      materialCount: printForm.value.materialCount,
      batchNumber: printForm.value.batchNumber
    };
  });

  axiosInstance.post('/api/warehouseMaterialTransferOrder/generateBatchNumber', param)
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        showPrint.value = false;
        printClick(res.data);
        handleEdit(formData.value, 1);

        // getList();
        // res.data.id
      });

};

const showPrint = ref(false);
const printForm = ref({
  materialCount: null,
  batchNumber: null
});
const doPrintShow = () => {
  showPrint.value = true;
  printForm.value = {
    materialCount: multipleSelection.value[0].materialCount,
    batchNumber: 1
  };
};


// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  currentPage.value = 1;
  // currentPage.value = 1
  getList();
};
const activeName = ref('detail');
const procedureOrderList = ref([]);
const wareList = ref([]);
const storageList = ref([]);
const searchStorageList = ref([]);

const wareSearchChange = (val) => {
  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: val,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        searchStorageList.value = res.data.records
        searchParam.value.targetStorageId = res.data.records.map(item => item.id);
        // getList()
      });
};


const materiaList = ref([]);
const showOutIn = ref(false);
const outInForm = ref({
  materialName: '',
  batchNo: '',
  materialCount: '',
  wareId: '',
  targetStorageId: ''
});
const outInFormRef = ref(null);
const formRef = ref(null);

const rules = reactive<FormRules<formRef>>({
  targetStorageId: [
    {required: true, message: '请选择入库库位', trigger: 'change'}
  ],
  businessType: [
    {required: true, message: '请选择业务类型', trigger: 'change'}
  ],
  outsourcingId: [
    {required: true, message: '请选择委外单号', trigger: 'change'}
  ],
  supplierId: [
    {required: true, message: '请选择供应商', trigger: 'change'}
  ]
});
const outInRules = reactive<FormRules<outInForm>>({
  materialCount: [
    {required: true, message: '请输入数量', trigger: 'blur'}
  ],
  wareId: [
    {required: true, message: '请选择入库仓库', trigger: 'change'}
  ],
  targetStorageId: [
    {required: true, message: '请选择入库库位', trigger: 'change'}
  ],
  batchNo: [
    {required: true, message: '请输入批次号', trigger: 'blur'}
  ]
});
const businessTypeList = ref([
  {
    name: '采购入库',
    id: 1
  }, {
    name: '销售退库',
    id: 2
  }, {
    name: '生产退库',
    id: 3
  }, {
    name: '生产入库',
    id: 4
  }, {
    name: '调拨（入）',
    id: 5
  }, {
    name: '委外入库',
    id: 6
  }, {
    name: '线边备料（入）',
    id: 7
  }
]);
const handleAddConfigLine = () => {
  formData.value.details.push({
    materialId: null,
    materialCount: null,
    batch: moment().format('YYYYMMDD'),
    materiaList: materiaList.value
  });
};

const currentYear = ref<number>(moment().year());
const currentWeek = ref<number>(moment().week());
const currentDayNumber = ref<number>(moment().isoWeekday());
const convertToWeekdayNumber = (isoWeekday: number): number => {
  return isoWeekday === 7 ? 1 : isoWeekday + 1;
};


const getMaterialInfo = (index) => {
  formData.value.details[index].basicUnit = formData.value.details[index].materiaList.find(item => item.id == formData.value.details[index].materialId).basicUnit;
};


const qualityPlanChange = (e) => {
  let param = {};
  for (const item of schemeTaskList.value) {
    if (item.id == e) {
      param = item;
    }
  }
  let json = JSON.parse(param.qualityJson);
  formQuality.value = {...formQuality.value, ...json};
  formQuality.value.qualityJson = param.qualityJson;
  console.log(formQuality.value, 'param');
};

const handleQualitySave = async () => {
  const param = formQuality.value;
  param.qualityJson = JSON.stringify(param);
  console.log(param, 'param');
  if (!param.qualityPlan) {
    ElMessage.error('请选择质检方案');
    return false;
  }
  param.id = null;
  param.status = false;
  param.sourceNo = quFParam.value.code;
  param.batchNo = quParam.value.batchNo;
  let url = '/api/qualitySchemeTask/createMaterialTask';
  if (param.qualityType == 1 || param.qualityType == 2 || param.qualityType == 3 || param.qualityType == 4) {
    url = '/api/qualitySchemeTask/createWorkOrderTask';
  }
  axiosInstance.post(url, param)
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        showQuality.value = false;
        getList();
      });
};


const qualityTypeChange = (e) => {
  schemeTaskList.value = [];
  formQuality.value.qualityType = e
  if (e == 5) {
    axiosInstance.get('/api/basedataMaterial/' + quParam.value.materialId, {})
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          schemeTaskList.value = res.data.basedataQualitySchemeList.filter(item => item.qualityType == 5);
          if (schemeTaskList.value && schemeTaskList.value.length > 0) {
            formQuality.value.qualityPlan = schemeTaskList.value[0].id
            qualityPlanChange(schemeTaskList.value[0].id)
          }
        });
  } else {
    const param = {
      qualityType: e,
      current: 1,
      pageSize: 99999,
      materialId: quParam.value.materialId
    };
    axiosInstance.post('/api/basedataQualityScheme/getPage', param)
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          schemeTaskList.value = res.data.records;
          if (res.data.records && res.data.records.length > 0) {
            formQuality.value.qualityPlan = res.data.records[0].id
            qualityPlanChange(res.data.records[0].id)
          }
        });
  }
};

const showQuality = ref(false);
const formQuality = ref({});
const schemeTaskList = ref([]);
const qualityWayList = ref([{
  label: '全检',
  value: '1'
}, {
  label: '比例抽检',
  value: '2'
}, {
  label: '固定抽检',
  value: '3'
}, {
  label: '自定义抽检',
  value: '4'
}]);

// 确认入库 入库确认
const outInSum = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      const param = outInForm.value;

      outFatherInfo.value.details = [param];
      outFatherInfo.value.tasks = [param];

      const reportingDto = {};
      // 委外入库
      // if (outFatherInfo.businessType == 6) {
      // 	reportingDto.traceabilityBarcode = 'U';
      // }
      if (outFatherInfo.value.businessType == 6 && !param.traceabilityBarcode) {
        ElMessage.error('请输入追溯码');
        return false;
      }
      reportingDto.supplierId = outFatherInfo.value.supplierId;
      reportingDto.materialId = outInForm.value.materialId;
      reportingDto.traceabilityBarcode = param.traceabilityBarcode;
      outFatherInfo.value.reportingDto = reportingDto;
      outFatherInfo.value.materialTransferOrderDetailBatchId = outInForm.value.id;
      axiosInstance.post('/api/warehouseMaterialTransferOrder/inStock', outFatherInfo.value)
          .then((res) => {
            if (res.code !== 200) {
              ElMessage.warning(res.message);
              return false;
            }
            showOutIn.value = false;
            getList();
          });
    }
  });

};

const detailForm = ref({});

const quParam = ref({});
const quFParam = ref({});
const doQuality = (qu, quf) => {
  console.log(qu, quf)
  quParam.value = qu;
  quFParam.value = quf;
  formQuality.value = qu
  formQuality.value.qualityType = 5
  qualityTypeChange(5)
  showQuality.value = true;
};

const outFatherInfo = ref({});

const doOutIn = (row) => {
  outInForm.value = JSON.parse(JSON.stringify(row));
  // this.materialCount = JSON.parse(JSON.stringify(param.materialCount))
  // 循环列表 找出子单据的父级
  // 提交时只提交父级和该条子单据

  for (const item of paginatedData.value) {
    if (item.children && item.children.length > 0) {
      for (const items of item.children) {
        if (items.id === row.id) {
          outFatherInfo.value = item;
          outInForm.value.targetWarehouseId = item.targetWarehouseId;
          outInForm.value.targetStorageId = item.targetStorageId;
          wareChange(item.targetWarehouseId, 1);
        }
      }
    }
  }

  getWorkNO(row.materialId, outInForm.value.targetStorageId);

  showOutIn.value = true;
};
const getWorkNO = (mId, sId) => {
  const params = {
    materialId: mId,
    storageId: sId,
    current: 1,
    pageSize: 999999
  };
  axiosInstance.post('/api/warehouseStorageMaterial/pageByPojo', params).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }

    const loop = [];
    for (const item of res.data.records) {
      if (item.materialStatus == 1) {
        loop.push(item);
      }
    }
    batchNoList.value = loop;
  });
};

const handleConfigDelete = (e) => {
  formData.value.details.splice(e, 1);
};

const searchMaterialProperData = ref(false);

const wareChange = (e, type) => {
  if (!type) {
    formData.value.targetStorageId = null;
    outInForm.value.sourceStorageId = null;
    // searchParam.value.sourceStorageId = null;
  }
  let warehouseName = '';
  for (const item of wareList.value) {
    if (item.id == e) {
      warehouseName = item.warehouseName;
    }
    for (const items of item.sonList) {
      if (items.id == e) {
        warehouseName = items.warehouseName;
      }
    }
  }
  if (popType.value != 1) {
    formData.value.details = [{
      materialId: null,
      materialCount: null,
      batch: moment().format('YYYYMMDD')
    }];
  }

  searchMaterialProperData.value = warehouseName.includes('原材料');
  getMateriaList();
  // storageList.value = {}
  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: e,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        storageList.value = res.data.records;
        if (!showCrud.value && type != 1) {
          searchParam.value.targetStorageId = storageList.value.map(item => item.id)
        }
      });
};

const remoteMateriaList = (index, e) => {
  if (!e) {
    return false
  }
  const param = {
    current: 1, pageSize: 30, materialName: e
  };
  if (searchMaterialProperData.value) {
    param.materialProperties = '0';
  } else {
    delete param.materialProperties;
  }
  axiosInstance.post('/api/basedataMaterial/getPage', param).then(res => {
    formData.value.details[index].materiaList = res.data.records;
  });
};

const getMateriaList = () => {
  const param = {
    current: 1, pageSize: 30
  };
  if (searchMaterialProperData.value) {
    param.materialProperties = '0';
  } else {
    delete param.materialProperties;
  }
  axiosInstance.post('/api/basedataMaterial/getPage', param).then(res => {
    materiaList.value = res.data.records;
  });
};


const getOption = () => {
  axiosInstance
      .post('/api/outsourcingPlan/getAll', {}).then(res => {
    if (res.code == 200) {
      outsourcingList.value = res.data;
    }
  });

  axiosInstance
      .post('/api/basedataSupplier/getAll', {}).then(res => {
    if (res.code == 200) {
      supplierList.value = res.data;
    }
  });

  // axiosInstance
  // 	.post('/api/basedataMaterial/getAll', {}).then(res => {
  // 	if (res.code == 200) {
  // 		materiaList.value = res.data;
  // 	}
  // });

  axiosInstance.post('/api/planProcedureOrder/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        const list = res.data;
        const loop = [];
        for (const item of list) {
          loop.push(
              {
                value: item.id,
                label: item.materialName
              }
          );
        }
        procedureOrderList.value = list;
      });

  axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });

  // axiosInstance.post('/api/qualitySchemeTask/getPage', {})
  //     .then(res => {
  //       if (res.code !== 200) {
  //         ElMessage.error(res.message);
  //         return false
  //       }
  //       storageList.value = res.data
  //     })
};

const transferTypeFormatter = (row, column, cellValue) => {
  let name = null;
  businessTypeList.value.find(item => {
    if (item.id === row.businessType) {
      name = item.name;
    }
  });
  return name || '';
};

const getTypeName = (type: string) => {
  const name = typeList.value.find((item: any) => item.value === type);
  return name ? name.label : '';
};

const typeList = ref([
  {label: '未完成', value: '0'},
  {label: '已完成', value: '1'}
]);

const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

const transferType = ref({transferType: 'instock'});

// 新建记录
const handleAdd = () => {
  popType.value = 0;
  isEdit.value = false;
  storageList.value = []
  formData.value = {
    details: [{
      materialId: null,
      materialCount: null,
      batch: moment().format('YYYYMMDD'),
      materiaList: materiaList.value
    }]
  };
  showCrud.value = true;
};


const popType = ref(0);//0 编辑 1 只读

const batchNoList = ref([]);

const doFinish = (row) => {
  ElMessageBox.confirm('是否确认完结?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        axiosInstance.post('/api/warehouseMaterialTransferOrder/finish', {id: row.id})
            .then(res => {
              if (res.code !== 200) {
                ElMessage.error(res.message);
                return false;
              }
              ElMessage.success('完结成功');
              getList();
            });
      })
      .catch(() => {
        // 处理取消的情况，如果需要的话
      });
};

const formatStatus = (row, column, cellValue) => {
  switch (cellValue) {
    case 1:
      return '待处理';
    case 2:
      return '进行中';
    case 3:
      return '完结';
  }
};

// 编辑记录
const handleEdit = (row: any, type) => {
  isEdit.value = true;
  let form = JSON.parse(JSON.stringify(row));
  axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', {id: row.id}).then(res => {
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return false;
    }
    form.details = res.data.children;
    form.warehouseMaterialTransferOrderDetailBatchList = res.data.warehouseMaterialTransferOrderDetailBatchList;
    if (type) {
      // 查看详情
      formData.value = form;
      popType.value = type;
      activeName.value = 'detail';
      showDetail.value = true;
      console.log(formData.value, ' formData.value formData.value');
    } else {
      // 编辑
      formData.value = form;
      popType.value = 0;
      showCrud.value = true;
    }
    wareChange(row.targetWarehouseId, 1);
  });
};


// 保存记录
const handleSave = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      const param = formData.value;
      if (!formData.value.targetStorageId) {
        ElMessage.warning('请选择入库库位');
        return false;
      }
      if (param.details.length == 0) {
        ElMessage.warning('请选择物料');
        return false;
      }
      for (const item of param.details) {
        if (!item.materialId) {
          ElMessage.warning('请选择物料');
          return false;
        }
        if (!item.materialCount || item.materialCount === 0) {
          ElMessage.warning('请输入数量');
          return false;
        }


      }
      axiosInstance.post('/api/warehouseMaterialTransferOrder/save', {...param, ...transferType.value})
          .then((res) => {
            if (res.code !== 200) {
              ElMessage.error(res.message);
              return false;
            }
            showCrud.value = false;
            getList();
          });
    }
  });

};

// 展开行处理
const expandedRowKeys = ref<string[]>([]);
const handleExpandChange = (row: any, expandedRows: any[]) => {
  if (expandedRows.includes(row)) {
    rowChildren(row);
  } else {
    // getList();
  }
};

const rowChildren = (row: any) => {
  axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', {id: row.id}).then(res => {
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return false;
    }
    const traceabilityCodeList = res.data?.traceabilityCodeList || [];
    const childrenWithTraceability = res.data.warehouseMaterialTransferOrderDetailBatchList?.map(child => ({
      ...child,
      traceabilityCodeList
    })) || [];

    paginatedData.value = paginatedData.value.map((item) => {
      if (item.id === row.id) {
        return {...item, children: childrenWithTraceability};
      }
      return item;
    });
  });
};
// 委外列表
const outsourcingList = ref([]);
const supplierList = ref([]);

const pageTotal = ref(0);

// 获取列表
const getList = async () => {
  paginatedData.value = [];
  axiosInstance.post('/api/warehouseMaterialTransferOrder/listByPojoPage', {
    ...searchParam.value,
    current: currentPage.value,
    pageSize: pageSize.value,
    ...transferType.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records.map((item) => ({
          ...item,
          children: [],
          layer: 1,
          _loading: false
        }));
        pageTotal.value = res.data.total;
      });
};

onMounted(() => {
  getList();
  getOption();
  getMateriaList();
});
</script>
<style scoped lang="scss">
::v-deep(.center-input .el-input__inner) {
  text-align: center;
}
</style>
